import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '@/stores';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('../views/Login/index.vue'),
      meta: { title: '登录' }
    },
    {
      path: '/',
      component: () => import('@/views/Layout/index.vue'),
      redirect: '/home',
      children: [
        {
          path: '/home',
          component: () => import('@/views/Home/index.vue'),
          meta: { title: '首页' }
        },
        {
          path: '/article',
          component: () => import('@/views/Article/index.vue'),
          meta: { title: '健康百科' }
        },
        {
          path: '/notify',
          component: () => import('@/views/Notify/index.vue'),
          meta: { title: '消息通知' }
        },
        {
          path: '/user',
          component: () => import('@/views/User/index.vue'),
          meta: { title: '个人中心' }
        },
        {
          path: '/user/patient',
          component: () => import('@/views/User/PatientPage.vue'),
          meta: { title: '家庭档案' }
        },
        {
          path: '/test',
          component: () => import('@/views/TestPage/index.vue'),
          meta: { title: '测试' }
        }
      ]
    }
  ]
});
NProgress.configure({
  showSpinner: false
});
// 访问权限控制
router.beforeEach((to) => {
  // 进度条
  NProgress.start();
  // 用户仓库
  const store = useUserStore();
  // 不需要登录的页面，白名单
  const wihteList = ['/login', '/register'];
  // 已登录且要去登录页，跳转到首页
  if (store.user?.token && to.path === '/login') {
    return '/';
  }
  // 如果没有登录且不在白名单内，去登录
  if (!store.user?.token && !wihteList.includes(to.path)) {
    return '/login';
  }
});
router.afterEach((to) => {
  document.title = `${to.meta.title || ''}`;
  NProgress.done();
});
export default router;
